<template>
  <Svga v-if="param.loading" :width="100" :height="100"></Svga>
  <div v-else class="app-container">
    <div style="font-weight: 700;padding-bottom: 20px;">
      订单号：{{ rowData.orderNo }}
    </div>
    <Progress :userRole="'boxDeal_agent'" :invoiceStatus="rowData.invoiceStatus" :orderStatus="param.newStep" />

    <div class="order-info">
      <el-row style="margin-bottom: 10px">
        <el-button-group v-if="param.newStep >= 15">
          <el-button icon="edit" @click="param.drawerInvoiceInfo = true">查看发票</el-button>
        </el-button-group>
        <el-button-group v-if="param.newStep >= 25" style="margin-left:20px; ">
          <el-button icon="edit" @click="showPackingListInfo">查看提箱单</el-button>
        </el-button-group>
        <!-- <el-button-group v-if="param.newStep >= 30" style="margin-left:20px; ">
          <el-button icon="edit" @click="showPackingRecord">查看提箱记录</el-button>
        </el-button-group> -->
      </el-row>

      <el-row :gutter="10">
        <el-col :span="18">
          <el-card style="box-sizing: border-box;padding: 10px;position: relative;">
            <stamp v-if="![20, 25, 30, 35, 40, 45].includes(rowData.processBusinessType)" :rowData="rowData"
              :rentSource="5" :pageType="'dealBox'" style="margin:10px 50px;position: absolute;right: 0;" />
            <stampCancel v-else :rowData="rowData" :pageType="'dealBox'" :canceledType="rowData.canceledType"
              :rentSource="5" :roleType="'agent'" style="margin:10px 50px;" />
            <el-row :gutter="10">
              <el-col :span="24"><span style="font-size: 16px;font-weight: 600;">{{ rowData.companyName }}</span></el-col>
            </el-row>
            <el-row :gutter="40" class="marginTop20">
              <el-col :span="11"><Carousel v-bind="swiperData" ></Carousel></el-col>
              <el-col :span="12">
                <el-row>
                  <el-col :span="24" style="font-size: 18px;font-weight: 700;">{{ rowData.carryCityName }}</el-col>
                  <el-col :span="24">购箱城市:{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}</el-col>
                </el-row>
                <el-row class="marginTop20">
                  <el-col :span="5" class="marginTop10">购箱单价</el-col> <el-col :span="18" class="marginTop10" style="color: #ff0000;">{{ payCurrency }} {{ rowData.unitPrice }}</el-col>
                  <el-col :span="5" class="marginTop10">箱型</el-col> <el-col :span="18" class="marginTop10">{{ boxTypeFilter(rowData.boxType) }}</el-col>
                  <el-col :span="5" class="marginTop10">箱况</el-col> <el-col :span="18" class="marginTop10">{{ boxConditionFilter(rowData.boxCondition) }}</el-col>
                  <el-col :span="5" class="marginTop10">箱量</el-col> <el-col :span="18" class="marginTop10"> {{ rowData.boxQuantity }} &nbsp;个</el-col>
                  <!-- <el-col :span="5" class="marginTop10">购买箱号</el-col> <el-col :span="18" class="marginTop10"> {{ rowData.containerNo }}</el-col> -->
                </el-row>
              </el-col>
            </el-row>
          </el-card>
          <el-card class="pag-container">
            <span class="_before">订单信息</span>
            <el-form inline label-width="60px" style="margin-top: 10px;" label-position="left">
              <el-form-item>
                <div>预计提箱日期</div>
                <el-date-picker v-model="rowData.planPickupDate" disabled type="date" style="width:100%" />
              </el-form-item>
              <el-form-item>
                <div>支付方式</div>
                <el-select v-model="rowData.paymentMethod" disabled style="width:100%;min-width: 200px;"
                  placeholder="选择">
                  <el-option v-for="item in param.paymentMethodList" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <div>结算账期</div>
                <el-input v-model="rowData.period" disabled style="width:100%">
                  <template #suffix>天</template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <div>发票类型</div>
                <!--  5-增值税普通发票  10-增值税专用发票 15-形式发票 -->
                <!-- <el-input v-model="rowData.contacts" disabled style="width:100%"></el-input> -->

                <el-select v-model="rowData.invoiceType" disabled style="width:100%;min-width: 150px;">
                  <el-option v-for="item in param.invoiceTypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <div>联系人</div>
                <el-input v-model="rowData.contacts" disabled style="width:100%"></el-input>
              </el-form-item>
              <el-form-item>
                <div>联系电话</div>
                <areaTel v-model:firstValue="rowData.tel" v-model:secondValue="rowData.areaCode" :disabled="true"
                  style="width:100%">
                </areaTel>
                <!-- <el-input v-model="rowData.tel" disabled style="width:100%"></el-input> -->
              </el-form-item>
              <el-form-item style="min-width:600px">
                <div>留言</div>
                <el-input v-model="rowData.leaveMsg" disabled style="width:100%"></el-input>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
        <el-col :span="6">
          <boxFeeCard style="height: 100%;" :rowData="rowData"></boxFeeCard>
        </el-col>
      </el-row>
      <el-card class="pag-container">
        <el-row>
          <el-col :span="8"><span class="_before">购买箱号</span></el-col>
        </el-row>
        <el-table :data="formatContainer" border style="max-height: 300px;" :show-header="false" class="marginTop20">
          <el-table-column type="index" width="50" align="center"/>
          <el-table-column prop="containerNo0" label="Date" >
            <template #default="scope">
              <el-row  v-if="scope.row.containerNo0" justify="center" align="middle">
                <el-col :span="19"><el-input v-model="scope.row.containerNo0" disabled></el-input></el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="containerNo1" label="Date" >
            <template #default="scope">
              <el-row  v-if="scope.row.containerNo1" justify="center" align="middle">
                <el-col :span="19"><el-input v-model="scope.row.containerNo1" disabled></el-input></el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="containerNo2" label="Date" >
            <template #default="scope">
              <el-row  v-if="scope.row.containerNo2" justify="center" align="middle">
                <el-col :span="19"><el-input v-model="scope.row.containerNo2" disabled></el-input></el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="containerNo3" label="Date" >
            <template #default="scope">
              <el-row  v-if="scope.row.containerNo3" justify="center" align="middle">
                <el-col :span="19"><el-input v-model="scope.row.containerNo3" disabled></el-input></el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="containerNo4" label="Date" >
            <template #default="scope">
              <el-row  v-if="scope.row.containerNo4" justify="center" align="middle">
                <el-col :span="19"><el-input v-model="scope.row.containerNo4" disabled></el-input></el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="containerNo5" label="Date" >
            <template #default="scope">
              <el-row  v-if="scope.row.containerNo5" justify="center" align="middle">
                <el-col :span="19"><el-input v-model="scope.row.containerNo5" disabled></el-input></el-col>
              </el-row>
            </template>
          </el-table-column>

          <template #empty>
            <el-row>
              <el-col :offset="9" :span="2" style="position: relative;"><el-icon size="30px" style="position: absolute;top:15px;"><MessageBox /></el-icon></el-col>
              <el-col :span="12" class="text-left">暂无集装箱箱号数据</el-col>
            </el-row>
          </template>
        </el-table>
      </el-card>

      <el-card class="pag-container">
        <orderAllocationRead :rowData="allocationInfo" :readOnly="true"></orderAllocationRead>
      </el-card>

      <!-- 按钮/反馈信息展示 -->
      <el-card class="pag-container">
        <div v-if="rowData.rejectReason && rowData.currentNodeType == 5" style="text-align: center;">
          <span>拒绝原因：</span>{{ rowData.rejectReason }}
        </div>
        <div v-if="rowData.status == 40 && rowData.canceledType == 5" style="text-align: center;margin-bottom: 20px;">
          <span> 取消原因： </span>
          <span>{{ rowData.remark }} </span>
        </div>
        <div v-if="rowData.currentNodeType == 25" >
          <span class="_before">审核信息</span>
          <h4>
            <redStar />驳回原因
          </h4>
          <el-input type="textarea" :rows="4" v-model="rowData.reviewRemark" placeholder="请输入驳回原因" />
        </div>
        <div style="width:100%;text-align: center;margin-top: 10px;">
          <template v-if="rowData.status == 40 && rowData.canceledType == 5">
            <el-button @click="handleShowWarning('rejectCancel')" type="danger" round> 拒 绝 </el-button>
            <el-button v-if="rowData.currentNodeType == 10" @click="handleMakeSure" type="primary" round> 同 意
            </el-button>
          </template>
          <el-button v-if="param.newStep <= 15 && rowData.status != 3" @click="handleShowWarning('cancelOrder')" type="info">取消订单</el-button>
          <el-button v-if="rowData.invoiceStatus == 15 && rowData.payStatus == 5" @click="handleGoPay" type="warning" >立即支付</el-button>
          <template v-if="rowData.currentNodeType == 15">
            <el-button @click="handleShowWarning('rejectOrder')" type="danger"> 拒绝 </el-button>
            <el-button @click="handleMakeSure" type="primary"> 确认 </el-button>
          </template>
          <template v-if="rowData.currentNodeType == 25">
            <el-button @click="handleShowWarning('checkReject')" type="danger"> 驳回 </el-button>
            <el-button @click="handleMakeSure" type="primary"> 通过</el-button>
          </template>
          <el-button v-if="rowData.currentNodeType == 30 && rowData.status == 3" @click="showContract" type="primary">签署
          </el-button>
          <el-button v-if="rowData.currentNodeType == 30 && rowData.status == 3" @click="completeSigning(rowData.id)" type="primary">完成签署</el-button>
          <el-button v-if="param.newStep == 10 && rowData.invoiceStatus == 5" @click="param.drawer = true" type="success">申请发票</el-button>
        </div>
      </el-card>

      <el-row style="padding: 20px; text-align: center;">
        <div style="width:100%">
          
        </div>
      </el-row>
      <div v-if="param.newStep == 5" style="padding: 20px;width: 100%;text-align: center "> </div>
    </div>

    <!-- drawer -->
    <!-- 申请发票 -->
    <el-drawer v-model="param.drawer" :with-header="false" size="50%">
      <span class="_before">发票信息</span>
      <el-row justify="left" class="marginTop10 ruler-box"> 
          <el-col :span="24" align="middle" class="text-left" style="background-color: #f9f3d1;color: #666;">
            <el-icon style="color:#fba400;margin:0 5px;height: 40px;"><WarningFilled /></el-icon>
            温馨提示：发票的开票金额不包括优惠券支付部分
          </el-col>
          <el-col :span="24" style="margin: 8px 0;">一、发票开具规则：</el-col>
          <el-col :span="24" >1）下单提箱后，电子发票在48小时内自动开具(如在月初1-6号则48小时内开具)，您可登陆您的平台账户，在订单详情处下载PDF格式增值税普通发票（电子）；</el-col>
          <el-col :span="24" >2）发票开具金额为您实际支付金额，不包括优惠券支付金额；</el-col>
          <el-col :span="24" >3）您可点击申请开票并查看开票进度，如有疑问请联系集装箱公司；</el-col>
          <el-col :span="24" >4）部分省份的税局已推行全电发票，商家会根据税局要求开具，与电子普通发票具备同等法律效力。</el-col>
          <el-col :span="24" style="margin: 8px 0;">
            二、数电票是全面数字化电子发票，数电票的法律效力、基本用途等与现有纸质发票相同。其中，带有“增值税专用发票”字样的数电票，其法律效力基本用途与现有增值税专用发票相同；带有“普通发票”字样的数电票，其法律效力、基本用途与现有普通发票相同。
          </el-col>
          <el-col :span="24" style="margin: 8px 0;">三、根据国家税务政策，部分公司提供数电票。</el-col>
          <el-col :span="24" style="margin: 8px 0;">四、数电票无特定格式要求,增加了XML的数据电文格式便利交付,同时保留PDF格式，用户可根据公司需求自行选择版式进行下载。</el-col>
      </el-row>
      <el-row class="invoce-box marginTop20">
        <el-col :span="6" class="text-right">发票状态</el-col><el-col :offset="8" :span="8" style="text-left">{{ { 5: '未申请', 10: '待开票', 15: '已开票' }[rowData.invoiceStatus] }}</el-col>
        <el-col :span="6" class="text-right marginTop10">发票内容</el-col><el-col :offset="8" :span="8" class="marginTop10">企业</el-col>
        <el-col :span="6" class="text-right marginTop10">发票抬头</el-col><el-col :offset="8" :span="8" class="marginTop10">{{ rowData.invoiceTitle }}</el-col>
        <el-col :span="6" class="text-right marginTop10">联系卖家</el-col><el-col :offset="8" :span="8" class="marginTop10">{{ rowData.boxEastUserTel }}</el-col>
        <el-col :span="6" class="text-right marginTop10">在线咨询</el-col><el-col :offset="8" :span="8" class="marginTop10">
          <el-button icon="ChatDotSquare" type="primary" link >咨询</el-button>
        </el-col>
      </el-row>
      <span class="_before" style="">申请发票</span>
      <el-row class="marginTop20">
        <el-col :span="8" class="text-right marginTop10">发票类型:</el-col><el-col :offset="4" :span="8" class="marginTop10">{{ invoiceTypeFilter(rowData.invoiceType) || '普通发票' }}</el-col>
        <el-col :span="8" class="text-right marginTop10">企业名称:</el-col><el-col :offset="4" :span="8" class="marginTop10">
            <el-input v-model="rowData.invoiceTitle" maxlength="200" placeholder="企业名称最长不超200个字符"></el-input>
        </el-col>
        <el-col :span="8" class="text-right marginTop10">统一社会信用代码:</el-col><el-col :offset="4" :span="8" class="marginTop10">
            <el-input v-model.trim="rowData.invoiceTaxNum" @input="handleInput" maxlength="18" placeholder=""></el-input>
        </el-col>
        <el-col :span="24" class="text-center marginTop20" v-if="param.newStep == 10">
          <el-button @click="handleApplyInvoice" type="primary" >提交</el-button>
        </el-col>
      </el-row>
    </el-drawer>

    <!-- E签宝 -->
    <el-dialog v-model="param.dialogEVisibleWarning" @close="handleCloseEQianBao" title="签署" style="width: auto;">
      <iframe v-if="param.dialogEVisibleWarning" :src="param.longContractUrl" width="100%" height="800px"
        frameborder="0"></iframe>
    </el-dialog>

    <!-- 发票信息 -->
    <el-drawer v-model="param.drawerInvoiceInfo" :with-header="false" size="50%">
      <invoiceInfo :rowData="rowData" :param="param"></invoiceInfo>
    </el-drawer>

    <!-- 提箱单 -->
    <el-drawer v-model="param.drawer1" :with-header="false" size="40%">
      <span class="_before">提箱单信息</span>
      <el-row class="marginTop20">
        <el-col class="text-right" :span="8">售箱企业：</el-col>
        <el-col :offset="1" :span="12">{{ packing.companyName }}</el-col>
      </el-row>
      <el-row class="marginTop10">
        <el-col class="text-right" :span="8">提箱单号：</el-col>
        <el-col :offset="1" :span="12">{{ packing.packingNo }}</el-col>
      </el-row>
      <el-row class="marginTop10">
        <el-col class="text-right" :span="8">提箱单有效期范围：</el-col>
        <el-col :offset="1" :span="12">
          {{ formatDate(packing.packingValidityPeriodStart, 2) }}
          ~
          {{ formatDate(packing.packingValidityPeriodEnd, 2) }}
        </el-col>
      </el-row>
      <el-row class="marginTop10">
        <el-col class="text-right" :span="8">状态：</el-col>
        <el-col :offset="1"  :span="12">{{ statusFilter(packing.status) }}</el-col>
      </el-row>
      <el-row class="text-center marginTop20" style="background-color: #eee;border: 1px solid #ccc;height: 40px;line-height: 40px;">
        <el-col :span="8" style="border-right: 1px solid #ccc;">箱型</el-col>
        <el-col :span="8" style="border-right: 1px solid #ccc;">箱量</el-col>
        <el-col :span="8" style="border-right: 1px solid #ccc;">箱况</el-col>
      </el-row>
      <el-row class="text-center" style="border: 1px solid #ccc;color: #666;border-top: none;height: 30px;line-height: 30px;">
        <el-col :span="8" style="border-right: 1px solid #ccc;">{{boxInfo.boxTypeInfo1[packing.boxType]}}</el-col>
        <el-col :span="8" style="border-right: 1px solid #ccc;">{{packing.totalQuantity}}</el-col>
        <el-col :span="8" style="border-right: 1px solid #ccc;">{{boxInfo.boxConditionInfo2[packing.boxCondition]}}</el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="12">提箱单附件：</el-col>
        <el-col :span="12">12122</el-col>
      </el-row> -->
      
      
      <el-row justify="end" class="marginTop20">
          <el-col :span="4" class="text-right"> <el-button plain @click="param.drawer1=false">关闭</el-button></el-col>
          <el-col :span="4" class="text-right"><el-button type="primary" :disabled="param.btnPackingRec"  @click="param.drawer2=true">提箱记录</el-button></el-col>
      </el-row>
    </el-drawer>
    <el-drawer v-model="param.drawer2" :with-header="false" size="40%">
      <span class="_before">提箱记录</span>
      <el-row justify="end" class="marginTop20">
          <el-col :span="6">应提箱量：{{packing.totalQuantity}}个</el-col>
          <el-col :span="6">实提箱量：{{packing.packedQuantity}}个</el-col>
      </el-row>
      <el-row class="text-center marginTop20 drawerHeader">
        <el-col :span="6">箱号</el-col>
        <el-col :span="6">箱型</el-col>
        <el-col :span="6">箱况</el-col>
        <el-col :span="6">提箱日期</el-col>
      </el-row>
      <template v-for="(item,index) in packingRecord" :key="index"> 
        <el-row class="text-center drawerContent">
          <el-col :span="6">{{item.containerNo}}</el-col>
          <el-col :span="6">{{boxInfo.boxTypeInfo1[item.boxType]}}</el-col>
          <el-col :span="6">{{boxInfo.boxConditionInfo2[item.boxCondition]}}</el-col>
          <el-col :span="6">{{formatDate(item.packingDate,2)}}</el-col>
        </el-row>
      </template>
      
      <el-row justify="end" class="marginTop20">
        <el-col :span="4" class="text-right"> <el-button plain @click="param.drawer2=false" >关闭</el-button></el-col>
      </el-row>
    </el-drawer>

    <!-- 申请退款 -->
    <el-dialog v-model="param.dialogRefund" :with-header="false">
      <div style="font-weight: 700;font-size: 15px;border-bottom: 1px solid black;padding-bottom: 20px;">
        <span style="width:3px;background-color: #2158F3;"> &nbsp</span>&nbsp申请退款
      </div>
      <div style="margin-top: 20px;">
        <div>购箱信息</div>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-carousel trigger="click" style="margin-left: 100px;height: 200px;">
              <el-carousel-item v-for="item in rowData.mainFileList" :key="item">
                <img :src="item.url" style="height: 200px;" />
              </el-carousel-item>
            </el-carousel>
          </el-col>
          <el-col :span="12">
            <div style="font-size: 14px;text-align: left; box-sizing: border-box;padding: 0px 40px 0px 40px;">
              <el-row :gutter="10">
                <el-col :span="11">
                  <span style="font-weight: bolder;font-size: 16px;">{{ rowData.carryCityName }}</span>
                  <div style="margin-top: 20px;">
                    购箱城市：{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}
                  </div>
                </el-col>
              </el-row>
              <table style="font-size: 14px;width: 400px;margin-top: 30px; margin-bottom: 20px; text-align: left;">
              <tbody>
               
                <tr style="width: 100px;">
                  <td>购箱单价</td>
                  <td style="font-weight: 600;"> ￥&nbsp;{{ rowData.unitPrice }}</td>
                </tr>
                <tr>
                  <td>箱型</td>
                  <td>
                    {{ boxTypeFilter(rowData.boxType) }}
                  </td>
                </tr>
                <tr>
                  <td>箱况</td>
                  <td>
                    {{ boxConditionFilter(rowData.boxCondition) }}
                  </td>
                </tr>
                <tr>
                  <td style="width:80px; ">箱量</td>
                  <td>
                    <span> &nbsp;{{ rowData.boxQuantity }} &nbsp;个</span>
                  </td>
                </tr>
                <tr>
                  <td style="width:80px; ">实付购箱费</td>
                  <td>
                    <span>￥&nbsp;{{ rowData.actualPayAmount }} </span>
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
          </el-col>
        </el-row>
      </div>
      <div style="margin-top: 20px">
        <div>退款信息</div>
        <table style="margin: 10px 0 30px 100px;">
          <tbody>
          <tr>
            <td style="width:80px; ">退还箱量：</td>
            <td>
              <el-input-number v-model="param.refundNumber" :precision="0" min="1" :max="rowData.boxQuantity"
                style="width:150px;"></el-input-number>
              &nbsp;个
            </td>
          </tr>
          <tr>
            <td style="width:80px; ">退款金额：</td>
            <td>
              <span>￥&nbsp;{{ refundAmount }} </span>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
      <div style="margin-top: 20px">退款原因</div>
      <el-input v-model="param.refundMark" type="textarea" rows="2" show-word-limit maxlength="200"></el-input>
      <div style="width: 100%;text-align: center;margin-top: 20px;">
        <el-button type="primary" @click="handleRefund">提交</el-button>
      </div>
    </el-dialog>

    <!-- 支付 -->
    <el-dialog v-model="param.dialogVisible" style="width:500px;box-sizing:bolder;padding:40px "
      :before-close="handleClose">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>支付购箱费
      </span>
      <table style="font-size: 14px;width: 400px;margin-top: 30px;">
        <tbody>
        <tr style="width: 100px;">
          <td>箱型</td>
          <td>{{ boxTypeFilter(rowData.boxType) }}</td>
        </tr>
        <tr>
          <td>应购箱量</td>
          <td>{{ rowData.boxQuantity }}</td>
        </tr>
        <tr>
          <td>实购箱量</td>
          <td>{{ rowData.boxQuantity }}</td>
        </tr>
        <tr>
          <td>应付购箱费</td>
          <td>￥ {{ rowData.amount }}</td>
        </tr>
        <tr>
          <td>实付购箱费</td>
          <td>￥ {{ rowData.amount }}</td>
        </tr>
        <tr>
          <td>优惠券</td>
          <td>{{ rowData.couponAmount }}</td>
        </tr>
        </tbody>
      </table>
      <el-form style="margin-top: 20px">
        <el-form-item>
          <redStar />
          <div>支付方式</div>
          <el-select v-model="rowData.paymentMethod" style="width:100%;min-width: 200px;" placeholder="选择">
            <el-option v-for="item in param.paymentMethodList" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <redStar />
          <div>电子回执单</div>
          <input type="file" style="width:100%" />
        </el-form-item>
        <el-form-item>
          <redStar />
          <div>支付日期</div>
          <el-date-picker v-model="rowData.payDate" type="date" style="width:100%" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlePay" style="margin-top: 40px;text-align: right;">提交</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <!-- 提示 -->
    <el-dialog v-model="param.dialogVisibleWarning" title="提示" style="width: 400px;">
      <el-form>
        <el-form-item v-if="param.warningName == 'cancelOrder'">
          <h3>确定取消订单吗？</h3>
        </el-form-item>
        <el-form-item prop="remark">
          <div style="width: 100%;">
            <span v-if="param.warningName == 'cancelOrder'">取消原因：</span>
            <span v-else-if="param.warningName == 'rejectOrder'">拒绝原因：</span>
            <span v-else>驳回原因：</span>
          </div>
          <el-input v-model="warningForm.remark" type="textarea" rows="3" max="200" show-word-limit placeholder="请输入"
            style="width: 300px;" />
        </el-form-item>
        <el-form-item>
          <el-button v-if="param.warningName == 'cancelOrder'" @click="handleCancel" type="primary"
            style="float: right;width: 100px;"> 确定
          </el-button>
          <el-button v-if="param.warningName == 'rejectOrder'" @click="handleReject('rejectOrder')" type="primary"
            style="float: right;width: 100px;"> 确定
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>
<script setup lang="ts">
import invoiceInfo from '@/views/components/order/invoiceInfo.vue'
import { formatDate } from '@/utils'
import Progress from '@/components/progress/index.vue'
import { computed, onActivated, onMounted, reactive, ref,getCurrentInstance } from 'vue';
import orderInfo from '@/store/modules/order'
import  Carousel from '@/components/carousel'
import { getOrderInfo, cancelPurchaseBoxOrderById, notarizePurchaseBoxOrder, applyRefundPurchaseBoxOrderById } from '@/api/boxDeal/boxBuy'
import { getPackingInfo, getPackingList } from '@/api/boxDeal/tiXiangManage'
import { buyBoxPage } from '@/api/boxDeal/tiXiangManageDetail'
import { payBoxLabelInvoice, addPurchaseBoxRequestInvoice, getInvoicesInfo } from '@/api/invoice'
import Svga from '@/views/components/Svga'
import boxFeeCard from '@/views/components/order/boxFeeCard.vue'
import orderAllocationRead from '@/views/components/order/orderAllocationRead.vue';
import invoiceTemplate from '@/views/components/invoiceTemplate.vue';
import redStar from '@/views/components/redStar.vue';
import { numMulti } from '@/utils/compute'
import { ElLoading, ElMessage, ElMessageBox, FormInstance, colProps } from 'element-plus';
import stamp from '@/views/components/stamp';
import stampCancel from '@/views/components/stamp/stampCancel';
import areaTel from '@/views/components/areaTel'
import boxInfo from '@/constant/containerInfo';

const formatContainer = computed(() => {
  if(rowData.value.containerNo){
    const newArr = rowData.value.containerNo?.split(",") 
    const chunkSize = 6;
    const result = [];
    let rowIndex = 0
    for (let i = 0; i < newArr.length; i += chunkSize) {
      const chunk = newArr.slice(i, i + chunkSize);
      const row = {};
      chunk.forEach((value, index) => {
        row[`containerNo${index}`] = value;
      });
      
      row['rowIndex'] = rowIndex
      rowIndex = rowIndex + 1
      result.push(row);
    }
    return result
  }
})

const param = reactive({
  loading: false,
  refundNumber: 1,
  num: 1,
  activeNames: '',
  drawer: false,
  drawer1: false,
  drawer2: false,
  btnPackingRec:true,
  dialogRefund: false,
  newStep: 1,
  dialogVisible: false,
 
  invoiceTypeList: [{ value: 5, label: '增值税普通发票' }, { value: 10, label: '增值税专用发票' }, { value: 15, label: '形式发票' }], // // 5-增值税普通发票  10-增值税专用发票 15-形式发票 
  //订单分配  
  paymentMethodList: [{ value: 5, label: '对公转账' }, { value: 10, label: '在线支付' }],
  operateUserList: [{ "operateUserId": 3, "operateUserName": "张三" }, { "operateUserId": 5, "operateUserName": "王五" }],
  businessUserList: [{ "businessUserId": 4, "businessUserName": "李四" }, { "businessUserId": 6, "businessUserName": "赵六" }],
  allocation: [{ 'operateUsers': [3, 5], "businessUser": 4, "businessNo": "NO1234567890" }], //[{"businessNo": "11111", "operateUserId": [3, 5], "businessUserId": 6}]
  containerNoArry: [],
  drawerInvoiceInfo:  false
})
//ruleForm
const ruleForm = reactive({
  invoiceTitle: [
    { required: true, message: '必填项', trigger: 'blur' }
  ],
  invoiceTaxNum: [
    { required: true, message: '必填项', trigger: 'blur' }
  ],
})
const swiperData = reactive({
  list: [],
  config: {
    width:"100%",
    height:"450px"
  }
})
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  let resut = false
  await formEl.validate((valid, fields) => {
    if (valid) {
      resut = true
    } else {
      resut = false
    }
  })
  return resut
}

const handleInput = (value) => {
      rowData.value.invoiceTaxNum = value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 18);        // 截断长度
  }
const ruleFormRef = ref()

//computed
const refundAmount = computed(() => {
  return numMulti(rowData.value.amount, param.refundNumber)
})
const payCurrency = computed(() => {
  return rowData.value.payCurrency == 'CNY' ? '￥' : '$'
})

onActivated(() => {
  resetForm(ruleFormRef.value)
  const rowData1 = orderInfo().rowData
  getSetOrderInfo(rowData1)
})

//获取数据
const rowData = ref({})
const allocationInfo = ref({})
const getSetOrderInfo = (row: any) => {
  if (!row.id) return
  getOrderInfo(row.id).then((res: any) => {
    param.newStep = res.data.status
    rowData.value = res.data
    allocationInfo.value = JSON.parse(res.data.allocation)
    swiperData.list = JSON.parse(res.data.mainFileList)
    rowData.value.allocation = JSON.parse(res.data.allocation)
    param.rate = res.data.rate || null
  })
}

//申请发票
const handleApplyInvoice = async () => {
  // let resut = await submitForm(ruleFormRef.value)
  // if (!resut) {
  //   return ElMessage({ message: '请完善信息', type: 'warning' })
  // }
  if(rowData.value.invoiceTitle && rowData.value.invoiceTaxNum && rowData.value.invoiceType){
    const data = {
      "invoiceOrder": JSON.stringify([{ orderId: rowData.value.id, orderNo: rowData.value.orderNo }]),
      "invoiceTitle": rowData.value?.invoiceTitle,
      "invoiceContent": "申请发票",
      "creditCode": rowData.value.invoiceTaxNum,
      "tel": rowData.value.tel
    }
    addPurchaseBoxRequestInvoice(data).then((res: any) => {
      getSetOrderInfo(rowData.value)
      param.drawer = false
    })
  }else{
    ElMessage({ message: '请完善信息', type: 'warning' })
  }
}

const handlePay = () => {
  if (!rowData.value.amount) {
    return ElMessage({ message: '购箱费不能为空', type: 'warning' })
  }
  const data = {
    "id": rowData.value.invoiceId, //发票id
    "paymentMethod": rowData.value.paymentMethod,
    "payDate": rowData.value.payDate,
    "payUrl": "[{\"name\":\"20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\",\"returnReceiptFileName\":\"国际贸易供应链数字平台电子回执单.docx\",\"url\":\"http://47.122.3.254:9000/default/20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\"}]",
    "couponAmount": 0, // 优惠
    "actualPayAmount": rowData.value.amount || 0,
  }
  payBoxLabelInvoice(data).then(res => {
    param.newStep = 25
    param.dialogVisible = false
    console.log('pay!')
  })
}


//  # purchaseBoxOrder: 退款信息   id 购箱订单明细Id refundQuantity: 退款数量
//  # couponAmount：优惠券金额
//  # remark: 备注
const handleRefund = () => {
  if (!param.refundMark) {
    return ElMessage.warning('请输入退款原因')
  }
  let purchaseBoxOrder = [{
    id: rowData.value.id,
    refundQuantity: param.refundNumber
  }]
  const data = {
    "purchaseBoxOrder": JSON.stringify(purchaseBoxOrder), //"[{\"id\": 5,\"refundQuantity\": 1},{\"id\": 6,\"refundQuantity\": 1}]",
    "couponAmount": 0,
    "remark": param.refundMark
  }
  applyRefundPurchaseBoxOrderById(data).then(res => {
    getSetOrderInfo(rowData.value)
    param.dialogRefund = false
    ElMessage({ message: '退款申请已提交', type: 'success' })
  })
}

const showInvoice = async () => {
  getInvoicesInfo(rowData.value.invoiceId).then((res: any) => {
    let data = res.data
    rowData.value.invoiceTitle = data.invoiceTitle
    rowData.value.invoiceTaxNum = data.creditCode
    rowData.value.invoiceType = data.invoiceType
    rowData.value.invoiceStatus = data.invoiceStatus
  })
  param.drawer = true
}

//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const invoiceTypeFilter = (val: any) => {
  if (val) {
    const filterCode = { 5: '增值税普通发票', 10: '增值税专用发票', 15: '形式发票' } // 5 - 增值税普通发票  10 - 增值税专用发票 15 - 形式发票
    return filterCode[val]
  }
}
const statusFilter = (val: any) => {
  let status = { 5: '已发放', 10: '已下载', 15: '提箱中', 20: '已完成' }
  return status[val]
}




//待确认->通过、确认 btn
import { processApproved, processRejected } from '@/api/orderCheck/index'
const handleMakeSure = async () => {
  if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
  const data = { "processId": rowData.value.processId }
  param.loading = true
  processApproved(data).then(() => {
    ElMessage({ message: '确认成功', type: 'success' })
    getSetOrderInfo(rowData.value)
    param.loading = false
  }).catch(() => {
    param.loading = false
  })
}
//待确认->拒绝btn、审核->驳回
const handleReject = (val: String) => {
  if (val == 'rejectOrder') { //拒绝
    if (!warningForm.value || !warningForm.value.remark) {
      return ElMessage({ message: '请输入拒绝 原因', type: 'warning' })
    }
    if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
    const data = { "processId": rowData.value.processId, "reviewRemark": warningForm.value.remark }
    processRejected(data).then(() => {
      ElMessage({ message: '拒绝成功', type: 'success' })
      param.dialogVisibleWarning = false
      getSetOrderInfo(rowData.value)
      // orderInfo().setOrderInfo(rowData.value)
    })
  }
  if (val == 'checkReject') { //驳回
    if (!rowData.value || !rowData.value.reviewRemark) {
      return ElMessage({ message: '请输入驳回 原因', type: 'warning' })
    }
    if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
    const data = { "processId": rowData.value.processId, "reviewRemark": rowData.value.reviewRemark }
    processRejected(data).then(() => {
      ElMessage({ message: '驳回成功', type: 'success' })
      getSetOrderInfo(rowData.value)
    })
  }
}
//待确认->驳回 btn 
// const handleReject = () => {
//   if (!rowData.value || !rowData.value.reviewRemark) {
//     return ElMessage({ message: '请输入驳回 原因', type: 'warning' })
//   }
//   if (!rowData.value || !rowData.value.processId) return ElMessage({ message: 'processId 未找到！', type: 'error' })
//   const data = { "processId": rowData.value.processId, "reviewRemark": rowData.value.reviewRemark }
//   processRejected(data).then(() => {
//     ElMessage({ message: '驳回成功', type: 'success' })
//     getSetOrderInfo(rowData.value)
//   })
// }

//show 提示窗口 
const handleShowWarning = (val: String) => {
  if (val == 'cancelOrder' || val == 'rejectCancel' || val == 'rejectOrder') { //取消订单、拒绝取消
    param.dialogVisibleWarning = true
    param.warningName = val
  }
  if (val == 'checkReject') { //审核驳回
    handleReject('checkReject')
  }
}

// 取消
import { cancelOrder } from '@/api/orderManage/index'
const warningForm = ref({ remark: '' })
const handleCancel = () => {
  if (!warningForm.value) {
    return ElMessage({ message: '请输入取消原因', type: 'warning' })
  }
  const data = {
    id: rowData.value.id,
    remark: warningForm.value.remark
  }
  cancelOrder(data).then(res => {
    // param.newStep = 35
    param.dialogVisibleWarning = false
    getSetOrderInfo(rowData.value)
  })
}

// 调取 eQuanBao 长链接
import { getContractList } from '@/api/contract/eQianBao'
import { spawn } from 'child_process';
const showContract = async (val: any) => {
  param.loading = true
  getContractList({ "orderId": rowData.value.id, "businessType":"15" }).then((res: any) => {
    param.longContractUrl = res.data[0].longContractUrl
    if (param.longContractUrl) {
      param.dialogEVisibleWarning = true
    } else {
      return ElMessage.warning('系统繁忙！请稍后再试')
    }
    param.loading = false
  }).catch(() => {
    ElMessage.warning('系统繁忙！请稍后再试')
    param.loading = false
  })
}

// 关闭弹窗
const handleCloseEQianBao = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '数据更新中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  await setTimeout(async () => {
    getSetOrderInfo(rowData.value)
    loading.close()
  }, 10000)
}
//查看提箱单
const packing = ref({})
const packingRecord= ref([])
const showPackingListInfo = ()=>{
  if(!rowData.value.id) return ElMessage.warning('提箱单不存在')
  getPackingList(rowData.value.id).then(res => {
    packing.value = res.data
    param.drawer1 = true 
    showPackingRecord(res.data.packingNo)

  }).catch((error) => {
    ElMessage.error(error)
  })
 
}
// 查看提箱记录
const showPackingRecord = (val:string) =>{
  const reqParameters = {
      packingNo:val,
      pageNum: 1,
      pageSize: 10
    }
  buyBoxPage(reqParameters).then(res => {
    // param.drawer2 = true 
    if(res.data.list && res.data.list.length > 0){
      param.btnPackingRec = false
    }
    packingRecord.value = res.data.list
  }).catch((error) => {
    ElMessage.error(error)
  })
  
  

}


const { proxy } = getCurrentInstance()
const completeSigning = (id) => { 
  let reqParam = { // 5:租箱 10：回调（进口） 15：购箱 
    orderId:id,
    businessType:15
  }
  proxy.$common(reqParam).then((res) => { 
    if(res.code === "00000"){
      ElMessage.success('操作成功')
    }else{
      ElMessage.warning(res.msg)
    }
  })
}
</script>

<style lang="scss" scoped>
.order-info {
  margin-top: 10px;
}

.pag-container {
  margin-top: 10px;
  box-sizing: border-box;
  padding: 10px;
}

table>tr>td~td {
  font-weight: bold;
}

.ruler-box .el-col{
    margin: 5px 0;
    color: #333;
  }
  .invoce-box{
    border-top: 1px solid #ddd;
    border-bottom: 1px solid #ddd;
    padding: 20px 0;
    margin-bottom: 20px;
  }
  .drawerHeader{
    height: 40px;
    line-height: 40px;
    background-color: #eee;
    border: 1px solid #ccc;
    border-right: none;
    .el-col{
      border-right: 1px solid #ccc;
    }
  }
  .drawerContent{
    height: 40px;
    line-height: 40px;
    border: 1px solid #ccc;
    border-right: none;
    border-top: none;
    .el-col{
      border-right: 1px solid #ccc;
    }
  }
</style>